package at.rtm.web;

import at.rtm.dao.HRDTemperatureDAOImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;

/**
 * The main controller displays all temperatures collected.
 */
@Controller
public class ChartController {
    @Autowired
    HRDTemperatureDAOImpl temperatureDataDAO;

    @RequestMapping(value = "chart.html")
    public String handleRequest(HttpServletRequest req, HttpServletResponse resp, Model model) {
        try {
            UrlResource chartURL = new UrlResource("http://chart.apis.google.com/chart?chxl=0:|Jan|Feb|Mar|Jun|Jul|Aug|1:|100|50|0");
            copy(chartURL.getInputStream(), resp.getOutputStream(), 4096);


        } catch (MalformedURLException e) {
            throw new IllegalStateException(e.getMessage(), e);
        } catch (IOException e) {
            throw new IllegalStateException(e.getMessage(), e);
        }

        return null;

    }

    public static void copy(InputStream in, OutputStream out, int bufferSize)
            throws IOException {
        // Read bytes and write to destination until eof

        byte[] buf = new byte[bufferSize];
        int len = 0;
        while ((len = in.read(buf)) >= 0) {
            out.write(buf, 0, len);
        }
    }

}
